﻿#include "appmonitorwidget.h"
#include "ui_appmonitorwidget.h"
#include <QMessageBox>
#include "dbservice.h"
#include "appmonitortaskmanager.h"
#include <QFileDialog>

AppMonitorWidget::AppMonitorWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AppMonitorWidget)
{
    ui->setupUi(this);

    connect(ui->cancelButton, SIGNAL(clicked(bool)), this, SLOT(close()));
    connect(ui->saveButton, SIGNAL(clicked(bool)), this, SLOT(onSaveButtonClicked()));
    connect(ui->delButton, SIGNAL(clicked(bool)), this, SLOT(onDeleteButtonClicked()));
    connect(ui->selectCmdButton, SIGNAL(clicked(bool)), this, SLOT(onSelectCmdClicked()));
    connect(ui->selectPidButton, SIGNAL(clicked(bool)),this, SLOT(onSelecPidFileClicked()));
    connect(ui->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int)));

    ui->intervalLineEdit->setValidator(new QRegExpValidator(QRegExp("^[0-9]*[1-9][0-9]*$"), this));
    ui->typeComboBox->setCurrentIndex(MonitorType_pid);


}

AppMonitorWidget::~AppMonitorWidget()
{
    delete ui;
}



 void AppMonitorWidget::prepareUpdateAppMointor(AppMonitor &appMonitor)
 {
     this->appMonitor = appMonitor;

     ui->nameLineEdite->setEnabled(true);


     ui->nameLineEdite->setText(this->appMonitor.name);
     ui->typeComboBox->setCurrentIndex(this->appMonitor.type);
     ui->settingLineEdit->setText(this->appMonitor.cfgInfo);
     ui->startCmdLineEdit->setText(this->appMonitor.startCmd);
     ui->intervalLineEdit->setText(int2QStr(this->appMonitor.checkIntervalSeconds));
     ui->maxMemUseKBLineEdit->setText(int2QStr(this->appMonitor.maxMemLimitKB/1024));
     setWindowTitle("修改");
 }

 void AppMonitorWidget::prepareCreateAppMointor()
 {

     ui->delButton->hide();
     setWindowTitle("新增");
 }



 void AppMonitorWidget::onSaveButtonClicked()
 {
    if(ui->nameLineEdite->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "名称不能为空");
        return;
    }

    if(ui->settingLineEdit->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "设置不能为空");
        return;
    }


    if(ui->intervalLineEdit->text().length() <= 0 || atoi(QStr2CStr(ui->intervalLineEdit->text())) <= 0)
    {
        QMessageBox::information(this, "提示", "监控时间间隔不能为空,且必须大于0");
        return;
    }

    if(ui->startCmdLineEdit->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "启动命令不能为空,且必须大于0");
        return;
    }

    if(ui->maxMemUseKBLineEdit->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "最大内存使用不能为空");
        return;
    }

    if(ui->typeComboBox->currentIndex() == MonitorType_appName && ui->settingLineEdit->text().length() > 25)
    {
        QMessageBox::information(this, "提示", "appName监控，监控的进程过长，最多25个字符");
        return;
    }

    AppMonitor tempMonitor = appMonitor;
    tempMonitor.name = ui->nameLineEdite->text();
    tempMonitor.type = ui->typeComboBox->currentIndex();
    tempMonitor.cfgInfo = ui->settingLineEdit->text();
    tempMonitor.checkIntervalSeconds = atoi(QStr2CStr(ui->intervalLineEdit->text()));
    tempMonitor.startCmd = ui->startCmdLineEdit->text();
    tempMonitor.maxMemLimitKB = atoi(QStr2CStr(ui->maxMemUseKBLineEdit->text()))*1024;

    if(tempMonitor.id >= 0 )
    {
        AppMonitorTask* task = gAppMonitorTaskManager.getTaskByAppMonitor(tempMonitor);
        if(task && task->state == RunableStateStarted)
        {
            if(QMessageBox::Yes ==  QMessageBox::information(this, "提示", "监控正在执行中,确认停止监听然后保存吗?",QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
            {
                task->stopAndWaitThreadQuit();
            }
            else
            {
                return;
            }
        }
    }


    if(f_success == gDBService.saveOneAppMonitor(tempMonitor))
    {
        QMessageBox::information(this,"提示", "保存任务成功");
        gAppMonitorTaskManager.oneAppMointorUpdated(tempMonitor);
        close();

    }
    else
    {
        QMessageBox::information(this,"提示", "保存任务失败");
    }

 }

 void AppMonitorWidget::onDeleteButtonClicked()
 {
     if(appMonitor.id > 0)
     {
         if(QMessageBox::Yes ==  QMessageBox::information(this, "提示", "确认删除该监控吗?",QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
         {
            if(f_success == gDBService.deleteOneAppMonitor(appMonitor))
            {
                gAppMonitorTaskManager.oneAppMointorDeleted(appMonitor);
                QMessageBox::information(this, "提示", "删除应用成功");
                close();
            }
            else
            {
                QMessageBox::warning(this, "提示", "删除应用失败");
            }
         }
     }
 }


 void AppMonitorWidget::onSelecPidFileClicked()
 {
     QString fileName = QFileDialog::getOpenFileName( this, "选择pid文件", QDir::currentPath(), "*.pid");
     ui->settingLineEdit->setText(fileName);
 }

 void AppMonitorWidget::onSelectCmdClicked()
 {
    QString fileName = QFileDialog::getOpenFileName( this, "选择可执行文件", QDir::currentPath(), "*.exe *.bat");
    ui->startCmdLineEdit->setText(fileName);
 }

 void AppMonitorWidget::typeChanged(int index)
 {
     ui->settingLineEdit->setText("");
    if(index == MonitorType_pid)
    {
        ui->selectPidButton->show();
        ui->settingCommemtLable->setText("请输入pid文件路径");
        ui->settingLineEdit->setValidator(NULL);
    }
    else if(index == MonitorType_appName)
    {
        ui->selectPidButton->hide();
        ui->settingCommemtLable->setText("请输入应用名称,注意大小写,并已exe结尾");
        ui->settingLineEdit->setValidator(NULL);
    }
    else if (index == MonitorType_listenSocket)
    {
        ui->selectPidButton->hide();
        ui->settingCommemtLable->setText("请输入需要监听的端口号");
        ui->settingLineEdit->setValidator(new QRegExpValidator(QRegExp("^[0-9]*[1-9][0-9]*$"), this));
    }
 }

void AppMonitorWidget::on_appNameCombox_currentIndexChanged(const QString &arg1)
{
    if(arg1.compare("其他") == 0)
    {
        ui->nameLineEdite->setText(appMonitor.name);
        ui->nameLineEdite->setEnabled(true);
    }
    else
    {
        ui->nameLineEdite->setText(arg1);
        ui->nameLineEdite->setEnabled(false);
    }
}
